package com.zp.base.admin.controller;

import java.util.*;

import com.zp.base.admin.vo.RoleVo;
import com.zp.base.admin.common.annotation.AddGroup;
import com.zp.base.admin.common.annotation.UpdateGroup;
import com.zp.base.admin.common.aspect.AddOperatorLog;
import com.zp.base.admin.common.constant.BizCodeEnum;
import com.zp.base.admin.common.utils.PageUtils;
import com.zp.base.admin.common.utils.R;
import com.zp.base.admin.common.utils.ValidUtil;
import com.zp.base.admin.config.SiteConfig;
import com.zp.base.admin.entity.MenuEntity;
import com.zp.base.admin.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.zp.base.admin.entity.RoleEntity;
import com.zp.base.admin.service.RoleService;


/**
 * 
 *
 * @author zhangpeng
 * @email zhangpeng@aliyun.com
 * @date 2021-02-28 11:15:56
 */
@Controller
@RequestMapping("admin/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private SiteConfig siteConfig;

    /**
     *
     * @param name  角色名称
     * @param page  当前页
     * @param model
     * @return
     */
    @GetMapping("/list")
    @AddOperatorLog(content = "查看了角色列表")
    @PreAuthorize("hasAuthority('role:list')")
    public String list(@RequestParam(name = "name", defaultValue = "") String name,
                       @RequestParam(name = "currentPage", defaultValue = "1") String page, Model model){
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("page", page);
        PageUtils pageUtils = roleService.queryPage(map);

        model.addAttribute("pageBean", pageUtils);
        model.addAttribute("title","角色列表");
        model.addAttribute("name",name);
        model.addAttribute("siteName", siteConfig.getSiteName());
        return "admin/role/list";
    }


    @GetMapping("/add")
    @PreAuthorize(value = "hasAuthority('role:add')")
    public String toAdd(Model model){
        //获取所有一级菜单信息（包含子类菜单信息）
        List<MenuEntity> menuEntityList = menuService.getAllMenus();

        model.addAttribute("menus", menuEntityList);
        model.addAttribute("title","角色列表");
        model.addAttribute("siteName", siteConfig.getSiteName());
        return "admin/role/add";
    }

    /**
     * 保存
     */
    @PostMapping("/add")
    @AddOperatorLog(content = "添加了角色")
    @ResponseBody
    @PreAuthorize("hasAuthority('role:add')")
    public R save(@Validated({AddGroup.class}) RoleVo addRoleVo, BindingResult bindingResult){
        //检查菜单信息  使用JSR303校验
        if (bindingResult.hasErrors()) {
            return ValidUtil.getErrorInfo(bindingResult);
        }
        addRoleVo.setCreateTime(new Date());
        addRoleVo.setUpdateTime(new Date());

        boolean save = roleService.addRole(addRoleVo);
        if (!save) {
            return R.error(BizCodeEnum.ADD_ROLE_FAIL_SERVER_EXCEPTION.getCode(), BizCodeEnum.ADD_ROLE_FAIL_SERVER_EXCEPTION.getMsg());
        }
        return R.ok();
    }

    /**
     * 去修改页面
     */
    @GetMapping("/edit")
    @PreAuthorize("hasAuthority('role:edit')")
    public String toEdit(@RequestParam(name = "id")Long id, Model model){
        //获取所有一级菜单信息（包含子类菜单信息）
        List<MenuEntity> menuEntityList = menuService.getAllMenus();
        model.addAttribute("title","角色列表");
        model.addAttribute("menus", menuEntityList);
        model.addAttribute("siteName", siteConfig.getSiteName());
        RoleEntity roleEntity = roleService.selectByRoleId(id);
        model.addAttribute("role", roleEntity);
        return "admin/role/edit";
    }

    /**
     * 修改
     */
    @PostMapping("/edit")
    @AddOperatorLog(content = "修改了角色信息")
    @ResponseBody
    @PreAuthorize("hasAuthority('role:edit')")
    public R edit(@Validated(UpdateGroup.class) RoleVo updateRoleVo, BindingResult bindingResult){
        //检查菜单信息  使用JSR303校验
        if (bindingResult.hasErrors()) {
            return ValidUtil.getErrorInfo(bindingResult);
        }
        updateRoleVo.setUpdateTime(new Date());
        boolean update = roleService.updateRole(updateRoleVo);
        if (!update) {
            return R.error(BizCodeEnum.UPDATE_ROLE_FAIL_SERVER_EXCEPTION.getCode(), BizCodeEnum.UPDATE_ROLE_FAIL_SERVER_EXCEPTION.getMsg());
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ResponseBody
    @AddOperatorLog(content = "删除了角色信息")
    @PreAuthorize("hasAuthority('role:delete')")
    public R delete(@RequestParam(name = "id") Long id){
        Integer del = roleService.deleteRoleById(id);
        if (del == 1) {
            return R.error(BizCodeEnum.DELETE_ROLE_FAIL_HAS_USER.getCode(), BizCodeEnum.DELETE_ROLE_FAIL_HAS_USER.getMsg());
        } else if (del == 2) {
            return R.error(BizCodeEnum.DELETE_ROLE_FAIL_SERVER_EXCEPTION.getCode(), BizCodeEnum.DELETE_ROLE_FAIL_SERVER_EXCEPTION.getMsg());
        }
        return R.ok();
    }

}
